<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="title"
    width="640px"
    @ok="onSave"
    okText="保存"
    :maskClosable="false"
  >
    <div class="panel">
      <BasicForm @register="registerForm1" class="form">
        <template #tel>
          <a-form-item-rest>
            <a-flex class="tel-group" align="center">
              <a-input
                v-model:value="form.areaCode"
                class="tel-1"
                placeholder="区号"
                :maxlength="4"
              />
              <div class="sep"></div>
              <a-input v-model:value="form.tel" class="tel-2" placeholder="电话" :maxlength="8" />
            </a-flex>
          </a-form-item-rest>
        </template>

        <template #image="{ field }">
          <Attachment
            accept="image/png, image/jpeg'"
            list-type="picture-card"
            :multiple="false"
            :maxCount="1"
            :disabled="false"
            v-model:data-source="form[field]"
          />
        </template>

        <template #week>
          <div>
            <BasicTable @register="registerTable" class="pb-16px" :dataSource="operatingPeriodDS">
              <template #action="{ record }">
                <TableAction
                  :divider="true"
                  :actions="[
                    {
                      color: 'success',
                      label: '修改',
                      onClick: () => onEditWeek(record),
                    },
                    {
                      popConfirm: {
                        title: '您确定要删除吗',
                        confirm: () => onDeleteWeek(record),
                      },
                      color: 'success',
                      label: '删除',
                    },
                  ]"
                />
              </template>
            </BasicTable>

            <a-button @click="onAddWeek" danger>
              <template #icon>
                <PlusOutlined />
              </template>
              增加一行
            </a-button>
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>
  <WeekDialog @register="registerWeek" @complete="onCompleteWeek" />
</template>
<script>
  import { defineComponent, reactive, ref, toRefs, h, watch } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import pca from '@/api/pca.json';

  import Attachment from '@/widget/attachment.vue';
  import { PlusOutlined } from '@ant-design/icons-vue';

  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import { useModal } from '@/components/Modal';

  import WeekDialog from './week.vue';
  import { POST } from '@/api/http';
  import { useMessage } from '@/hooks/web/useMessage';
  import {
    deleteOperatingPeriod,
    formatOperatingPeriod,
    getOperatingPeriodWeek,
  } from '@/views/basics/shop/util';
  import { getAttachment, initImgAttachment } from '@/api/util.js';
  import { parsePca, formatPca } from '@/api/ds';

  export default defineComponent({
    name: 'ShopDetail',
    components: {
      BasicTable,
      TableAction,
      Attachment,
      BasicDrawer,
      BasicForm,
      PlusOutlined,
      WeekDialog,
    },
    emits: ['complete'],
    setup(_, { emit }) {
      const [registerWeek, { openModal: weekModal }] = useModal();
      const { createMessage } = useMessage();

      const state = reactive({ form: { areaCode: '', tel: '' }, title: '', operatingPeriodDS: [] });

      const [registerForm1, form1] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24, style: { paddingRight: '36px' } },

        schemas: [
          {
            label: '所在区域',
            field: 'pca',
            required: false,
            component: 'Cascader',
            componentProps: {
              showSearch: true,
              options: pca,
              fieldNames: { label: 'name', value: 'code' },
            },
          },

          {
            label: '详细地址',
            field: 'storeAddr',
            required: false,
            component: 'InputTextArea',
          },

          {
            label: '营业时间',
            field: 'operatingPeriod',
            required: false,
            component: 'InputGroup',
            slot: 'week',
          },

          {
            label: '门店座机',
            field: 'storeLandline',
            component: 'InputGroup',
            slot: 'tel',
            rules: [
              { required: false },
              { pattern: /^(\d{3,4})-(\d{7,8})$/, message: '请输入正确的座机' },
            ],
          },

          {
            label: '门店手机',
            field: 'storeMobile',
            component: 'Input',
            rules: [
              { required: false },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
            ],
          },

          {
            label: '门头照片',
            field: 'doorstepImgurl',
            required: false,
            component: 'upload',
            slot: 'image',
          },

          {
            label: '营业执照',
            field: 'bizlicImgurl',
            required: false,
            component: 'upload',
            slot: 'image',
          },
        ],
        showActionButtonGroup: false,
      });

      const [registerTable] = useTable({
        columns: [
          {
            title: '星期',
            dataIndex: 'weekDesc',
            width: '33%',
            ellipsis: false,
            customRender: ({ value }) => h('span', { innerHTML: value }),
          },

          {
            title: '时间段',
            dataIndex: 'timeDesc',
            ellipsis: false,
            customRender: ({ value }) => h('span', { innerHTML: value }),
          },
        ],
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        showIndexColumn: false,
        pagination: false,
        scroll: { y: 180 },
        actionColumn: {
          title: '操作',
          align: 'center',
          width: 120,
          dataIndex: 'action',
          fixed: 'right',
          slots: { customRender: 'action' },
        },
      });

      const recordRef = ref({});
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(
        async ({ behavior }) => {
          state.title = behavior === 'edit' ? '编辑档案' : '档案详情';

          try {
            setDrawerProps({ confirmLoading: true });

            POST('/shop/getStoreInfoByPara').then((list) => {
              const detail = list?.[0] ?? {};

              //省市区
              const { storeRca } = detail;
              detail.pca = parsePca(storeRca);

              recordRef.value = detail;
              form1.setFieldsValue(detail);

              //营业时间
              state.operatingPeriodDS = formatOperatingPeriod(detail.operatingPeriod);

              //座机
              let { storeLandline } = detail;
              storeLandline ||= '';

              if (storeLandline.indexOf('-') < 0) {
                storeLandline = '-' + storeLandline;
              }

              const [areaCode = '', tel = ''] = storeLandline.split('-');
              Object.assign(state.form, { areaCode, tel });

              //附件
              Object.assign(
                state.form,
                initImgAttachment(recordRef.value, ['doorstepImgurl', 'bizlicImgurl']),
              );
            });
          } finally {
            setDrawerProps({ confirmLoading: false });
          }
        },
      );

      watch(
        () => {
          const { areaCode, tel } = state.form;
          return [areaCode, tel];
        },
        (array) => {
          form1.setFieldsValue({ storeLandline: array.filter((s) => !!s).join('-') });
        },
      );

      async function onSave() {
        await form1.validate();
        const formData = form1.getFieldsValue();

        //省市区
        const { pca: list } = formData;
        formData.storeRca = formatPca(list);

        //营业时间
        formData.operatingPeriod = JSON.stringify(getOperatingPeriodWeek(state.operatingPeriodDS));

        //附件
        const { doorstepImgurl, bizlicImgurl } = state.form;
        formData.doorstepImgurl = getAttachment(doorstepImgurl)?.[0]?.url ?? null;
        formData.bizlicImgurl = getAttachment(bizlicImgurl)?.[0]?.url ?? null;

        try {
          setDrawerProps({ confirmLoading: true });

          const data = { ...recordRef.value, ...formData };
          await POST('/shop/updateStoreInfo', data);
          createMessage.success('门店信息已保存');

          emit('complete');
          closeDrawer();
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function onAddWeek() {
        const { operatingPeriodDS } = state;
        weekModal(true, { behavior: 'add', operatingPeriodDS });
      }

      function onEditWeek(record) {
        const { operatingPeriodDS } = state;
        weekModal(true, { behavior: 'edit', operatingPeriodDS, record });
      }

      function onDeleteWeek({ startTime, endTime }) {
        state.operatingPeriodDS = deleteOperatingPeriod(
          state.operatingPeriodDS,
          startTime,
          endTime,
        );
      }

      function onCompleteWeek(list) {
        state.operatingPeriodDS = [...list];
      }

      return {
        ...toRefs(state),
        registerDrawer,
        registerForm1,
        onSave,
        registerTable,
        registerWeek,
        onAddWeek,
        onDeleteWeek,
        onEditWeek,
        onCompleteWeek,
      };
    },
  });
</script>

<style lang="less" scoped>
  .panel {
    .form {
      padding: 24px 0 0;

      .tel-group {
        .tel-1 {
          width: 80px !important;
        }

        .sep {
          display: inline-block;
          width: 12px;
          height: 2px;
          margin: 0 12px;
          background-color: #ced5df;
        }

        .tel-2 {
          flex: 1;
          width: auto !important;
        }
      }
    }

    ::v-deep(.ant-form-item-control-input) {
      .ant-select,
      .ant-input-affix-wrapper,
      .tel-group {
        width: 300px;
      }
    }

    .table {
      position: relative;
      top: 6px;
      left: -74px;
    }

    ::v-deep(.vben-basic-table .ant-table-wrapper) {
      padding: 0;
    }
  }
</style>
